package com.fin.zw.intelligentbot.service;

import com.fin.zw.intelligentbot.entity.Company;
import com.fin.zw.intelligentbot.entity.CorpusInfo;
import com.fin.zw.intelligentbot.entity.QCorpusInfo;
import com.fin.zw.intelligentbot.entity.SceneInfo;
import com.fin.zw.intelligentbot.model.request.LibraryInfoRequest;
import com.fin.zw.intelligentbot.model.session.SessionModel;
import com.fin.zw.intelligentbot.repository.CorpusRepository;
import com.fin.zw.intelligentbot.repository.SceneInfoRepository;
import com.google.common.collect.Lists;
import com.querydsl.core.BooleanBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

@Service("corpusService")
public class CorpusService {

    private static Logger logger = LoggerFactory.getLogger(CorpusService.class);

    @Value("${file.library}")
    private String fileLibrary;

    @Autowired
    private CorpusRepository corpusRepository;

    @Autowired
    private SceneInfoRepository sceneInfoRepository;

    @Autowired
    private CommonService commonService;

    @Autowired
    private LibraryFileService libraryFileService;

    /**
     * 分页查询
     * @param pageable
     * @param sessionModel
     * @return
     */
    public Page<CorpusInfo> queryLibraryInfo(Pageable pageable,
                                             SessionModel sessionModel) {
        BooleanBuilder builder = new BooleanBuilder();
        QCorpusInfo qCorpusInfo = QCorpusInfo.corpusInfo;
        if(sessionModel.getCompanyId() != null){
            builder.and(qCorpusInfo.company.id.eq(sessionModel.getCompanyId()));
        }
        Page<CorpusInfo> page = corpusRepository.findAll(builder, pageable);
        return page;
    }

    /**
     * 不分页查询
     * @param sessionModel
     * @return
     */
    public List<CorpusInfo> getLibraryInfos(SessionModel sessionModel) {
        BooleanBuilder builder = new BooleanBuilder();
        QCorpusInfo qCorpusInfo = QCorpusInfo.corpusInfo;
        builder.and(qCorpusInfo.company.id.eq(sessionModel.getCompanyId()));
        if(sessionModel.getCompanyId() != null){
            builder.and(qCorpusInfo.company.id.eq(sessionModel.getCompanyId()));
        }
        Iterator<CorpusInfo> infoIterator = corpusRepository.findAll(builder).iterator();
        return Lists.newArrayList(infoIterator);
    }

    public void createLibraryInfo(LibraryInfoRequest request, SessionModel sessionModel, MultipartFile file) throws IOException {
        CorpusInfo corpusInfo = new CorpusInfo();
        BeanUtils.copyProperties(request, corpusInfo);
        Company company = commonService.getCompany(sessionModel);
        corpusInfo.setCompany(company);
        if (StringUtils.isNotEmpty(request.getSceId())) {
            SceneInfo sceneInfo = sceneInfoRepository.findById(request.getSceId()).orElseThrow(() -> new RuntimeException("选择的场景信息不存在！"));
            corpusInfo.setSceneInfo(sceneInfo);
        }
        if (file != null) {
            String url = libraryFileService.saveFileLibrary(file, fileLibrary, sessionModel);
            corpusInfo.setFile(url);
        }
        corpusInfo.setCreateTime(new Date());
        corpusInfo.setUserId(sessionModel.getUserId());
        corpusInfo.setUserName(sessionModel.getUserName());
        corpusRepository.save(corpusInfo);
    }

    /**
     * 语音信息更新
     * @param request
     * @param sessionModel
     * @throws IOException
     */
    public void updateLibraryInfo(LibraryInfoRequest request,SessionModel sessionModel,MultipartFile file) throws IOException {
        CorpusInfo corpusInfo = checkExist(request.getId());
        BeanUtils.copyProperties(request, corpusInfo);
        if (StringUtils.isNotEmpty(request.getSceId())) {
            SceneInfo sceneInfo = sceneInfoRepository.findById(request.getSceId()).orElseThrow(() -> new RuntimeException("选择的场景信息不存在！"));
            corpusInfo.setSceneInfo(sceneInfo);
        }
        if (file != null) {
            String url = libraryFileService.saveFileLibrary(file, fileLibrary, sessionModel);
            corpusInfo.setFile(url);
        }
        corpusRepository.save(corpusInfo);
    }

    /**
     * 语音库的删除
     * @param id
     */
    public void deleteInfo(String id) {
        CorpusInfo libraryInfo = checkExist(id);
        corpusRepository.delete(libraryInfo);
    }

    /**
     * 检测权限
     * @param id
     * @return
     */
    private CorpusInfo checkExist(String id) {
        Optional<CorpusInfo> optional = corpusRepository.findById(id);
        if(!optional.isPresent()){
            logger.info("更新的语音信息不存在");
            throw new RuntimeException("更新的语音信息不存在");
        }
        CorpusInfo libraryInfo = optional.get();
        return libraryInfo;
    }
}
